<template>
	<page-wrapper :show-tab-bar="false" :navTitle="isEdit ? '编辑预算分类' : '添加预算分类'" navBackgroundColor="#FFD84D">
		<view class="budget-category-edit-page">
			<!-- 自定义导航栏 -->
			<!-- <CustomNavbar :title="isEdit ? '编辑预算分类' : '添加预算分类'" backgroundColor="#FFD84D"></CustomNavbar> -->

			<!-- 表单区域 -->
			<view class="form-container">
				<!-- 分类名称 -->
				<view class="form-item">
					<text class="form-label">分类名称</text>
					<input type="text" v-model="formData.name" class="form-input" placeholder="请输入分类名称" />
				</view>

				<!-- 预算金额 -->
				<view class="form-item">
					<text class="form-label">预算金额</text>
					<input type="digit" v-model="formData.amount" class="form-input" placeholder="请输入预算金额" />
				</view>

				<!-- 已用金额 (只读，仅编辑模式显示) -->
				<view class="form-item" v-if="isEdit && formData.spent > 0">
					<text class="form-label">已用金额</text>
					<view class="form-value">{{ formData.spent.toFixed(2) }}</view>
					<view class="progress-bar">
						<view class="progress-inner"
							:style="{ width: progressPercent + '%', backgroundColor: progressColor }"></view>
					</view>
				</view>
			</view>

			<!-- 分类选择区域 -->
			<view class="category-container">
				<text class="section-title">选择分类</text>
				<scroll-view scroll-y class="category-scroll"
					:style="{ height: categoryScrollHeight }">
					<view class="category-list">
						<view v-for="(category, index) in systemCategories" :key="category.id" class="category-item"
							:class="{ active: formData.categoryId === category.id }" @click="selectCategory(category)">
							<view class="category-icon" :style="{ backgroundColor: category.color + '20' }">
								<image v-if="category.icon" :src="category.icon" class="category-icon-image"
									mode="aspectFit"></image>
								<uni-icons v-else type="wallet" size="24"
									:color="formData.categoryId === category.id ? category.color : '#333'"></uni-icons>
							</view>
							<text class="category-name">{{ category.name }}</text>
						</view>
					</view>
				</scroll-view>
			</view>


			<view class="bottom-container">
				<!-- 保存按钮 -->
				<view class="save-btn" @click="saveCategory">
					<text>保存</text>
				</view>
				<!-- 删除按钮 (仅编辑模式显示) -->
				<view class="delete-btn" @click="confirmDelete" v-if="isEdit">
					<text>删除此预算分类</text>
				</view>
			</view>
		</view>
	</page-wrapper>
</template>

<script>
import { themeMixin } from '@/utils/theme.js';
import { addBudgetCategory, updateBudgetCategory, deleteBudgetCategory, getBudgetCategoryDetail } from '@/api/budget-category.js';
import { queryCategories } from '@/api/category.js';

export default {
	mixins: [themeMixin],
	data() {
		return {
			// 是否为编辑模式
			isEdit: false,

			// 表单数据
			formData: {
				id: null,        // 预算分类ID
				budgetId: null,  // 预算ID
				categoryId: null, // 分类ID
				name: '',        // 分类名称
				amount: '',      // 预算金额
				spent: 0,        // 已用金额
				year: null,      // 年份
				month: null      // 月份
			},

			// 系统分类列表
			systemCategories: [],
			
			// 系统状态栏高度
			statusBarHeight:0
		};
	},
	computed: {
		// 计算进度百分比
		progressPercent() {
			if (parseFloat(this.formData.amount) <= 0) return 0;
			return Math.min((this.formData.spent / parseFloat(this.formData.amount)) * 100, 100);
		},

		// 计算进度条颜色
		progressColor() {
			const remaining = parseFloat(this.formData.amount) - this.formData.spent;

			if (remaining < 0) {
				return '#F44336'; // 红色，超预算
			} else if (remaining <= parseFloat(this.formData.amount) * 0.2) {
				return '#FF9800'; // 橙色，预算即将用完
			} else {
				return '#4CAF50'; // 绿色，预算充足
			}
		},
		// 动态计算分类选择区高度，兼容APP/小程序状态栏
		categoryScrollHeight() {
			let base = this.isEdit ? 870 : 700;
			let statusBar = 0;
			// #ifdef APP-PLUS || MP
			statusBar = this.statusBarHeight;
			// #endif
			return `calc(100vh - ${base}rpx - ${statusBar}px)`;
		}
	},
	onLoad(options) {
		// 获取系统分类
		this.fetchSystemCategories();

		// 判断是否为编辑模式
		if (options.categoryData) {
			// 如果传入了完整的分类数据对象
			try {
				const category = JSON.parse(decodeURIComponent(options.categoryData));
				this.setFormData(category);
				this.isEdit = true;
			} catch (e) {
				console.error('解析分类数据失败:', e);
				uni.showToast({
					title: '加载分类数据失败',
					icon: 'none'
				});
			}
		} else if (options.params) {
			// 新增模式，获取预算ID和年月
			try {
				const params = JSON.parse(decodeURIComponent(options.params));
				this.formData.budgetId = params.budgetId;
				this.formData.year = params.year;
				this.formData.month = params.month;
			} catch (e) {
				console.error('解析参数失败:', e);
			}
		}
		
		// 获取状态栏高度
		this.getStatusBarHeight();
	},
	methods: {
		// 获取状态栏高度
		getStatusBarHeight() {
		    // #ifdef APP-PLUS || MP
		    this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 0;
		    // #endif
		},
		
		// 获取系统分类列表
		fetchSystemCategories() {
			queryCategories({
				spend: 1,   // 支出类型
				page: 1,
				pageSize: 50
			})
				.then(res => {
					if (res.data.code === 200 && res.data.data) {
						this.systemCategories = res.data.data.records || [];

						// 如果有系统分类且还没有选择分类，默认选择第一个
						if (this.systemCategories.length > 0 && !this.formData.categoryId && !this.isEdit) {
							this.selectCategory(this.systemCategories[0]);
						}
					}
				})
				.catch(err => {
					console.error('获取系统分类失败:', err);
				});
		},

		// 加载分类数据
		loadCategoryData(id) {
			getBudgetCategoryDetail(id)
				.then(res => {
					if (res.data.code === 200 && res.data.data) {
						const budgetCategory = res.data.data;
						this.setFormData({
							id: budgetCategory.id,
							budgetId: budgetCategory.budgetId,
							categoryId: budgetCategory.categoryId,
							name: budgetCategory.category ? budgetCategory.category.name : '',
							amount: budgetCategory.amount,
							spent: budgetCategory.monthlyExpense || 0
						});
					}
				})
				.catch(err => {
					console.error('获取预算分类详情失败:', err);
					uni.showToast({
						title: '获取分类详情失败',
						icon: 'none'
					});
				});
		},

		// 设置表单数据
		setFormData(category) {
			this.formData.id = category.id;
			this.formData.budgetId = category.budgetId;
			this.formData.categoryId = category.categoryId;
			this.formData.name = category.name;
			this.formData.amount = category.amount.toString();
			this.formData.spent = category.spent || 0;
			this.formData.year = category.year;
			this.formData.month = category.month;
		},

		// 选择分类
		selectCategory(category) {
			this.formData.categoryId = category.id;
			this.formData.name = category.name;
		},

		// 保存分类
		saveCategory() {
			// 表单验证
			if (!this.formData.categoryId) {
				uni.showToast({
					title: '请选择分类',
					icon: 'none'
				});
				return;
			}

			const amount = parseFloat(this.formData.amount);
			if (isNaN(amount) || amount <= 0) {
				uni.showToast({
					title: '请输入有效的预算金额',
					icon: 'none'
				});
				return;
			}

			// 构建预算分类对象
			const budgetCategory = {
				id: this.isEdit ? this.formData.id : null,
				budgetId: this.formData.budgetId,
				categoryId: this.formData.categoryId,
				amount: amount,
				status: 1 // 启用状态
			};

			if (this.isEdit) {
				// 更新预算分类
				updateBudgetCategory(budgetCategory)
					.then(res => {
						if (res.data.code === 200) {
							uni.showToast({
								title: '更新成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.msg || '更新失败',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						console.error('更新预算分类失败:', err);
						uni.showToast({
							title: '更新失败，请重试',
							icon: 'none'
						});
					});
			} else {
				// 添加预算分类
				addBudgetCategory(budgetCategory)
					.then(res => {
						if (res.data.code === 200) {
							uni.showToast({
								title: '添加成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.msg || '添加失败',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						console.error('添加预算分类失败:', err);
						uni.showToast({
							title: '添加失败，请重试',
							icon: 'none'
						});
					});
			}
		},

		// 确认删除
		confirmDelete() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除此预算分类吗？',
				success: (res) => {
					if (res.confirm) {
						this.deleteCategory();
					}
				}
			});
		},

		// 删除分类
		deleteCategory() {
			if (!this.formData.id) {
				uni.showToast({
					title: '无法删除，分类ID不存在',
					icon: 'none'
				});
				return;
			}

			// 调用API删除分类
			deleteBudgetCategory(this.formData.id)
				.then(res => {
					if (res.data.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.data.msg || '删除失败',
							icon: 'none'
						});
					}
				})
				.catch(err => {
					console.error('删除预算分类失败:', err);
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					});
				});
		}
	}
}
</script>

<style lang="scss">
.budget-category-edit-page {
	display: flex;
	flex-direction: column;
	height: 100%;
	background-color: $background-color;

	// 表单区域
	.form-container {
		background-color: $card-background;
		padding: 30rpx;
		margin-bottom: 20rpx;

		.form-item {
			margin-bottom: 30rpx;

			.form-label {
				font-size: 28rpx;
				color: $text-color-light;
				margin-bottom: 15rpx;
				display: block;
			}

			.form-input {
				width: 100%;
				height: 80rpx;
				border-bottom: 1px solid $border-color;
				font-size: 32rpx;
				color: $text-color;
				padding: 0 10rpx;
			}

			.form-value {
				font-size: 32rpx;
				color: $text-color;
				padding: 10rpx 0;
			}

			.progress-bar {
				height: 10rpx;
				background-color: $color-progress-bg;
				border-radius: 5rpx;
				margin-top: 20rpx;
				overflow: hidden;

				.progress-inner {
					height: 100%;
					border-radius: 5rpx;
				}
			}
		}
	}

	// 分类选择区域
	.category-container {
		background-color: $card-background;
		padding: 30rpx 30rpx 0 30rpx;
		// margin-bottom: 20rpx;

		.section-title {
			font-size: 28rpx;
			color: $text-color-light;
			margin-bottom: 20rpx;
			display: block;
		}

		.category-list {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 20rpx;
			padding: 10rpx 0;
		}

		.category-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 15rpx 0;

			&.active {
				.category-icon {
					border: 2rpx solid currentColor;
					background-color: rgba(255, 107, 107, 0.1);
				}

				.category-name {
					color: $color-category-active;
				}
			}

			.category-icon {
				width: 80rpx;
				height: 80rpx;
				border-radius: $border-radius-circle;
				background-color: $color-category-bg;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-bottom: 10rpx;
				border: 2rpx solid transparent;

				.category-icon-image {
					width: 48rpx;
					height: 48rpx;
				}
			}

			.category-name {
				font-size: 24rpx;
				color: $text-color-light;
				text-align: center;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 100%;
			}
		}
	}

	.bottom-container {
		background-color: $card-background;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		gap: 20rpx;

		// 删除按钮
		.delete-btn {
			flex: 1;
			padding: 20rpx 0;
			display: flex;
			justify-content: center;
			background-color: rgba(255, 107, 107, 0.1);
			align-items: center;
			border: 2rpx solid $color-progress-danger;
			border-radius: $border-radius-large;

			text {
				font-size: 32rpx;
				color: $color-progress-danger;
			}
		}

		// 保存按钮
		.save-btn {
			flex: 1;
			padding: 20rpx 0;
			background-color: $primary-color;
			border-radius: $border-radius-large;
			display: flex;
			justify-content: center;
			align-items: center;

			text {
				font-size: 32rpx;
				color: $text-color-white;
				font-weight: bold;
			}
		}
	}
}
</style>